// Find file utilities
// Copyright (C) 2011-2012 Jani Kajala. Licensed under MIT-license.
// Dependencies: Node.js (only core modules)

var fs = require('fs');
var path = require('path');

/**
 * Returns list of files in specified directory and optionally recurses subdirectories.
 * @param dir Directory name.
 * @param recurse Recurse subdirectories. Default: false.
 * @return List of file names.
 */
var dirSync = function( dir, recurse, out ) {
	if (typeof out === 'undefined') out = [];
	var files = fs.readdirSync( dir, true );
	for ( var i = 0 ; i < files.length ; ++i ) {
		var fname = dir+'/'+files[i];
		out.push( fname );
		if (recurse) {
			var fstat = fs.statSync( fname );
			if (fstat.isDirectory())
				this.dirSync( fname, recurse, out );
		}
	}
	return out;
};

/**
 * Find files by matching filename part to regular expression.
 * @param regex Regular expression object
 * @param dir Starting directory
 * @param recurse Recurse subdirectories. Default: false.
 * @return List of file names.
 */
var pregFindFilesSync = function( regex, dir, recurse ) {
	if ( typeof regex === 'string' )
		regex = new RegExp( regex );
	var files0 = dirSync( dir, recurse );
	var files = [];
	for ( var i = 0 ; i < files0.length ; ++i ) {
		var fname = files0[i];
		if ( regex.test( path.basename(fname) ) )
			files.push( fname );
	}
	return files;
};

/**
 * Finds files using wildcards.
 * @param fname File name specifier with optional path. Accepts wildcard * and joker ?.
 * @param recurse Recurse subdirectories. Default: false.
 * @return List of file names.
 */
var findFilesSync = function( fname, recurse ) {
	var repl = {
		'.': '\\.',
		'*': '.*',
		'?': '.'
	};
	var base = path.basename(fname);
	for (var k in repl)
	{
		var v = repl[k];
		base = base.replace(k,v);
	}
	base = new RegExp( '^'+base+"$" );
	return pregFindFilesSync( base, path.dirname(fname), recurse );
};

//------------------------------------------------------------------------------------------------
// module.exports
//------------------------------------------------------------------------------------------------

module.exports = {
	dirSync: dirSync,
	pregFindFilesSync: pregFindFilesSync,
	findFilesSync: findFilesSync,
};
